﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Linq;

namespace Portal.Nhibernate.Repository
{
    public abstract class Repository<T> : IRepository<T> where T : IEntity
    {
        protected virtual ISession Session
        {
            get { return SessionBuilder.CreateSession(); }
        }


        public abstract T CreateEntity();

        /// <summary>
        ///返回一个实体 
        /// </summary>
        /// <returns></returns>


        public virtual IQueryable<T> Get()
        {

            return Session.Query<T>();
        }

        public virtual long Count()
        {
            return Session.Query<T>().Count();
        }

        public virtual IQueryable<T> Get(Expression<Func<T, bool>> expression)
        {
            return Session.Query<T>().Where(expression);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public virtual IQueryable<T> GetSort(string sort = "Id", string order = "DESC")
        {
            Check.Argument.IsNotNull(sort, "排序字段");
            Check.Argument.IsNotNull(order, "排序条件");
            return LinqHelper.DataSorting(Session.Query<T>(), sort, order);
        }

        /// <summary>
        /// 根据条件获取表IQueryable 
        /// </summary>
        /// <returns></returns>
        public virtual IQueryable<T> GetSort(Expression<Func<T, bool>> expression, string sort = "Id", string order = "DESC")
        {
            Check.Argument.IsNotNull(expression, "查询条件");
            Check.Argument.IsNotNull(sort, "排序字段");
            Check.Argument.IsNotNull(order, "排序条件");
            return LinqHelper.DataSorting(Session.Query<T>().Where(expression), sort, order);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t"></param>
        public void Add(T t)
        {
            Session.Save(t);
        }

        public void AddOrUpdate(T t)
        {
            Session.SaveOrUpdate(t);
        }

        public virtual void Delete(T t)
        {
            Session.Delete(t);
        }

        public virtual void Delete(Expression<Func<T, bool>> expression)
        {
            foreach (var item in Session.Query<T>().Where(expression))
            {
                Session.Delete(item);
            }
        }
        public virtual void Update(T t)
        {
            Session.Update(t);
        }

        public virtual void Save()
        {
            Session.Flush();
        }
    }
}
